//
//  NativeDemoVC.m
//  JAGatherAdDemo
//
//  Created by Yc on 2022/4/24.
//

#import "NativeDemoVC.h"
#import <JAGatherAdSDK/JAGatherAdSDK.h>
#import "PlacementVC.h"
#import <Masonry.h>
#import "NativeDemoCell.h"
#import "NativeSelfRenderAdView.h"
#import "NativeListDemoVC.h"

@interface NativeDemoVC () <JAGAdNativeDelegate>

@property (nonatomic, strong) JAGAdNative *native;

@property (nonatomic, assign) BOOL isLoadAndShow;

@property (nonatomic, strong) UIView *container;

@property (nonatomic, strong) NSMutableArray *dataArrM;

@end

@implementation NativeDemoVC

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self showNativeListAdButton];
    [self setupContainerFrame];
    
    self.placementList = [[NSMutableArray alloc] initWithArray:[self readPlacementDataOfType:DataType_nativeExpress]];
    [self setupPlacement:nativeID];
    [self creatNative];

}

- (void)setupContainerFrame {
    CGFloat containerY =  [self getNativeListAdButtonMaxY] + 15;
    CGFloat containerH = [UIScreen mainScreen].bounds.size.height - containerY;
    self.container.frame = CGRectMake(0, containerY, [UIScreen mainScreen].bounds.size.width , containerH);
}

- (void)viewWillLayoutSubviews {
    [super viewWillLayoutSubviews];
    [self setupContainerFrame];
}

- (void)creatNative {
    [self deallocAd];
    self.native = [[JAGAdNative alloc] initWithPlacementID:[self getPlacement] adSize:CGSizeMake(self.container.bounds.size.width, self.container.bounds.size.width/16*9)];
    self.native.viewController = self;
    self.native.delegate = self;

}

- (void)loadAdAction {
    [super loadAdAction];
    NSLog(@"%s", __FUNCTION__);
    TOAST(@"开始加载广告数据");
    [self resetState];
    self.isLoadAndShow = NO;
    [self.native loadAd];
    [self writePlacementDataOfType:DataType_nativeExpress];
}

- (void)showAdAction {
    [super showAdAction];
    NSLog(@"%s", __FUNCTION__);
    if (!self.native || !self.isLoaded || self.dataArrM.count == 0) {
        TOAST(@"请先加载广告数据");
        return;
    }
    [self showNativeAd];
}

- (void)loadAndShowAdAction {
    [super loadAndShowAdAction];
    NSLog(@"%s", __FUNCTION__);
    TOAST(@"开始加载广告数据");
    [self resetState];
    self.isLoadAndShow = YES;
    [self.native loadAndShowAd];
    [self writePlacementDataOfType:DataType_nativeExpress];
}

- (void)loadNativeListAdAction {
    NativeListDemoVC *listVc = [[NativeListDemoVC alloc] init];
    listVc.placement = [self getPlacement];
    [self.navigationController pushViewController:listVc animated:YES];
}

- (void)reselectPlacementAction {
    [self creatNative];
}

- (void)dealloc {
    NSLog(@"%s", __FUNCTION__);
}

- (void)deallocAd {
    self.native = nil;
    self.native.delegate = nil;
    [self resetState];
}

- (void)resetState {
    self.isLoaded = NO;
    [self.dataArrM removeAllObjects];
    [self.container.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)];
}

// 信息流广告比较特殊, 渲染逻辑需要自行处理
- (void)showNativeAd {
    
    JAGNativeFeedAdModel *adModel = self.dataArrM.firstObject;
    if (adModel.isNativeExpress) {
        // 模版广告需进行render 渲染后，模版视图feedView frame才能获取真实高度
        [adModel render];
        [self.container addSubview:adModel.feedView];
        
    } else {
        // NativeSelfRenderAdView 自渲染须设置Frame进行初始化，未设置影响广告容器绑定和曝光
        NativeSelfRenderAdView *adView = [[NativeSelfRenderAdView alloc] initWithFrame:CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, 120)];
        adView.adMeta = adModel.adMaterialMeta;
        __weak typeof(self) ws = self;
        [adView setTapDislikeBlock:^{
            __strong typeof(ws) self = ws;
            [self resetState];
        }];
        if (adModel.isNativeExpress) {
            [adModel registerContainer];
        } else {
            [adView unregisterDataObject];
            [adView registerDataObject];
        }
        [self.container addSubview:adView];
    }
}


#pragma mark - JAGAdNativeDelegate

/// 信息流广告加载成功
- (void)JAGatherNativedAdLoadSuccess:(JAGAdNative *)nativeAd feedAds:(NSArray <JAGNativeFeedAdModel *> *)feedAds {
    NSLog(@"%s", __FUNCTION__);
    
    for (JAGNativeFeedAdModel *adModel in feedAds) {
        
        if (!adModel.isNativeExpress && ![adModel.adMaterialMeta isAdValid]) {
            continue;
        }
        [self.dataArrM addObject:adModel];
    }
    
    self.isLoaded = YES;
    if (self.isLoadAndShow) {
        [self showNativeAd];
    }
    TOAST(@"数据加载完成");
}

/// 信息流广告加载失败
- (void)JAGatherNativeAdFailToLoad:(JAGAdNative *)nativeAd error:(NSError *)error {
    NSLog(@"%s %@", __FUNCTION__,error);
    NSString *msg = [NSString stringWithFormat:@"%@",error];
    TOAST(msg);
}

/// 信息流广告渲染成功
- (void)JAGatherNativeAdRenderSuccess:(JAGAdNative *)nativeAd feedAd:(JAGNativeFeedAdModel *)feedAd {
    NSLog(@"%s", __FUNCTION__);
    // 模版广告渲染成功 高度更新
}

/// 信息流广告渲染失败
- (void)JAGatherNativeAdRenderFail:(JAGAdNative *)nativeAd feedAd:(JAGNativeFeedAdModel *)feedAd error:(NSError *)error {
    NSLog(@"%s", __FUNCTION__);
    [self.container.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)];
    NSString *msg = [NSString stringWithFormat:@"广告渲染失败：%@",error];
    TOAST(msg);
}

/// 信息流广告曝光
- (void)JAGatherNativeAdDidExpourse:(JAGAdNative *)nativeAd feedAd:(JAGNativeFeedAdModel *)feedAd {
    NSLog(@"%s", __FUNCTION__);
}

/// 信息流广告点击
- (void)JAGatherNativeAdClicked:(JAGAdNative *)nativeAd feedAd:(JAGNativeFeedAdModel *)feedAd {
    NSLog(@"%s", __FUNCTION__);
}

/// 信息流广告关闭
- (void)JAGatherNativeAdClosed:(JAGAdNative *)nativeAd feedAd:(JAGNativeFeedAdModel *)feedAd {
    [self resetState];
    NSLog(@"%s", __FUNCTION__);
}

/// 信息流广告关闭落地页
- (void)JAGatherNativeAdDidCloseLandingPage:(JAGAdNative *)nativeAd feedAd:(JAGNativeFeedAdModel *)feedAd {
    NSLog(@"%s", __FUNCTION__);
}

/// 信息流视频广告播放状态
- (void)JAGatherNativeAdVideoDidChanged:(JAGAdNative *)nativeAd playState:(JAGVideoPlayState)playState feedAd:(JAGNativeFeedAdModel *)feedAd {
    NSLog(@"%s playState : %zd", __FUNCTION__ , playState);
}

#pragma mark - Lazy
- (UIView *)container {
    if (!_container) {
        _container = [[UIView alloc] init];
        [self.view addSubview:_container];
    }
    return _container;
}

- (NSMutableArray *)dataArrM {
    if (!_dataArrM) {
        _dataArrM = [[NSMutableArray alloc] init];
    }
    return _dataArrM;
}

@end
